package com.jackrain.nea.web.controller;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jackrain.nea.core.schema.Column;
import com.jackrain.nea.core.schema.Table;
import com.jackrain.nea.core.schema.TableManager;
import com.jackrain.nea.exception.NDSException;
import com.jackrain.nea.util.IsChineseOrNot;
import com.jackrain.nea.util.ValueHolder;
import com.jackrain.nea.web.face.User;
import com.jackrain.nea.web.face.impl.UserImpl;
import com.jackrain.nea.web.query.*;
import com.jackrain.nea.web.security.Directory;
import com.jackrain.nea.web.security.SecurityWebUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;


@Slf4j
@RestController
@Api(value = "SeachController", description = "关键字界面查询rest")
public class SeachController {

    @ApiOperation(value="关键字查询", notes="根据中文表名或英文名检索返回，有权限和不可用限制！")
    @RequestMapping(path = "/p/cs/SearchWords",method = {RequestMethod.GET,RequestMethod.POST})
    public JSONObject getSearchWords(HttpServletRequest request,
                                     @RequestParam(value="words", required=true)String words){

        ValueHolder valueHolder = new ValueHolder();

        UserImpl userWeb= (UserImpl)request.getSession().getAttribute("user");

        QuerySession qsession= QueryUtils.createQuerySession(userWeb);
        TableManager manager=qsession.getTableManager();

        QueryRequestImpl query = new com.jackrain.nea.core.db.QueryRequestImpl(qsession);
        String tableId="ad_table";
        Table table;
        table= manager.getTable(tableId);
        query.setMainTable(table.getId());
        query.addSelection(table.getColumn("description").getId());
        query.addSelection(table.getPrimaryKey().getId());
        query.addSelection(table.getColumn("name").getId());

        if(IsChineseOrNot.isChineseCharacter(words)){
            query.addParam(table.getColumn("description").getId(), words);
            query.addParam(table.getColumn("isactive").getId(),"=Y");
            query.addParam(table.getColumn("ismenuobj").getId(),"=Y");
        }else{
            query.addParam(table.getColumn("name").getId(), words);
            query.addParam(table.getColumn("isactive").getId(),"=Y");
            query.addParam(table.getColumn("ismenuobj").getId(),"=Y");
        }

        query.setRange(0, 10  );

        Expression sexpr= SecurityWebUtils.getSecurityFilter("ad_table",1,userWeb.id,qsession);// read permission
        
        Expression expr=new Expression(null, "exists (select 1 from AD_TABLECATEGORY t,ad_subsystem g where t.isactive='Y' and g.isactive='Y' and t.ad_subsystem_id=g.id and t.id=ad_table.ad_tablecategory_id)", null );
        
        if(expr!=null){
            sexpr=expr.combine(sexpr, SQLCombination.SQL_AND,null);
        }
        query.addParam(sexpr);
        log.debug("search words->"+query.toSQL());

        JSONArray vals= QueryEngine.getInstance().doQueryObjectArray(query.toSQL()+" limit 10");
        valueHolder.put("code",0);
        valueHolder.put("datas",vals);
//        QueryResultMetaData meta=result.getMetaData();
//        List b = new ArrayList();
//        List c = new ArrayList();
//        for(int j=0;j<result.getRowCount();j++){
//            result.next();
//            for(int k=1; k<=meta.getColumnCount();k++){
//                if(k%2==1){
//                    b.add(result.getObject(k));
//                }else{
//                    c.add(result.getObject(k));
//                }
//            }
//        }
//        JSONObject select_m=new org.json.JSONObject(attributeValues);
//        org.json.JSONObject jo=new org.json.JSONObject();
//        org.json.JSONArray  arr_key=new org.json.JSONArray(b);
//        org.json.JSONArray  arr_val=new org.json.JSONArray(c);
//        jo.put("query",queryexp);
//        jo.put("suggestions",arr_
        return  valueHolder.toJSONObject();
    }

    @ApiOperation(value="模糊查询", notes="根据输入键模糊查询")
    @RequestMapping(path = "/p/cs/fuzzyquerybyak",method = {RequestMethod.GET,RequestMethod.POST})
    public JSONObject fuzzyQueryByAK(HttpServletRequest request,
                                     @RequestParam(value="ak", required=true)String ak,
                                     @RequestParam(value="colid", required=true)int columnId){

        ValueHolder valueHolder = new ValueHolder();
        User userWeb= (User)request.getSession().getAttribute("user");
        QuerySession qsession= QueryUtils.createQuerySession(userWeb);
        TableManager manager=qsession.getTableManager();

        Column column = manager.getColumn(columnId);
        Table table = column.getReferenceTable();
        if(table == null){
            throw new NDSException("reference table is null");
        }

        String[] selection = new String[]{table.getPrimaryKey().getName(),table.getAlternateKey().getName()};
        String[] alias = new  String[]{"id","value"};

        String tableName;
        tableName = table.getName();
        if (table.isView()) {
            tableName = table.getRealTableName();
        }

        HashMap params = new HashMap();
        params.put(table.getAlternateKey().getName(),"LIKE '%" + ak + "%'");
        params.put("ISACTIVE","='Y'");
        params.put("AD_CLIENT_ID","="+userWeb.getClientId());

        StringBuffer sql = new StringBuffer("SELECT ");

        for(int i=0; i<selection.length; i++){
            sql.append(selection[i] + " " + alias[i] + ",");
        }
        sql.delete(sql.length()-1,sql.length());
        sql.append(" FROM " + tableName + " WHERE ");

        Iterator it = params.keySet().iterator();

        while (it.hasNext()){
            String key = (String)it.next();
            sql.append(key + " " + params.get(key) + " AND ");
        }
        sql.delete(sql.length()-4,sql.length());
        sql.append(" limit 10");

        if(!userWeb.isAdmin()){
            SecurityWebUtils.checkDirectoryReadPermission(table.getSecurityDirectory(manager),(UserImpl) userWeb);// read permission
        }

        log.debug("search ak->"+sql);

        JSONArray data= QueryEngine.getInstance().doQueryObjectArray(sql.toString());

        valueHolder.put("code",0);
        valueHolder.put("data",data);

        return  valueHolder.toJSONObject();
    }

}
